<?php 
// include 'common.php';
// session_start();
date_default_timezone_set("Asia/Shanghai");
class User
{	
	/**
	 * 数据库连接对象
	 * @var PDO
	 */
	private $_db;

	/**
	 * User construct
	 * @param PDO $db [description]
	 */
	public function __construct($db)
	{
		$this->_db = $db;
	}


	/**
	 * API启动方法
	 * @return [type] [description]
	 */
	public function run()
	{	

						$username = isset($_POST["username"])?$_POST["username"]:'';
						$password = isset($_POST["password"])?$_POST["password"]:'';
						$vcode    = isset($_POST["vcode"])?$_POST["vcode"]:'';
						$email    = isset($_POST["email"])?$_POST["email"]:'';
						$path     = isset($_SERVER["PATH_INFO"])?explode("/", $_SERVER["PATH_INFO"]):explode("/", $_SERVER["QUERY_STRING"]);
						        

		try{
				switch ($path[2]) {
					case 'register':
						
						$this->register($username,$password,$vcode,$email);
						break;

					case 'login':
						$this->login($email,$password);
						break;
					
					default:
						echo json_encode("参数不合法",400);
						break;
				}

				
			
		} catch(Exception $e){
			$this->_json($e->getMessage(),$e->getCode());
		}
	}


	/**
	 * 注册
	 * @param  str $username 用户名
	 * @param  str $password 密码
	 * @param  str $vcode    验证码
	 * @param  str $email    email
	 * @return [type]           [description]
	 */
	public function register($username, $password, $vcode, $email)
	{

		if(empty($username)){
			throw new Exception("用户名不能为空", 400);
		}

		if($this->_email($email)){
			throw new Exception("无效的 email 格式！", 400);
		}

		if(empty($password)){
			throw new Exception("密码不能为空", 400);
		}

		if($this->_vcode($vcode)){
			throw new Exception("验证码错误", 400);			
		}

		if($this->isUsernameExists($email)){
			throw new Exception("该用户已存在", 400);
			
		}

		// $username = rand(100000, 999999);
		$register_time = date("Y-m-d H:i:s");

		$sql = "insert into `user`(`username`,`password`,`email`,`register_time`,`status`) values(?,?,?,?,?)";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$username);
		$smt->bindParam(2,$password);
		$smt->bindParam(3,$email);
		$smt->bindParam(4,$register_time);
		$smt->bindParam(5,$status);
		if(!$smt->execute()){

			throw new Exception("注册失败", 405);
		}

		echo $this->_json("注册成功","200");
		exit;

	}

	/**
	 * json方法
	 * @param  str $message 错误信息
	 * @param  int $code    错误码
	 * @return json          [description]
	 */
	public function _json($message, $code)
	{	
		echo json_encode(["message"=>$message, "code"=>$code]);
		exit;
	}


	/**
	 * 检测用户名是否存在
	 * @param  string  $username 用户名
	 * @return boolean           [description]
	 */
	protected function isUsernameExists($email)
	{
		$sql = "select * from user where email = ?";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$email);
		$smt->execute();
		$row = $smt->fetch();

		if(!empty($row)){
			return true;
		}

		return false;
	}


	/**
	 * 加密函数
	 * @param  string $password 密码
	 * @return string           密码
	 */
	protected function _md5($password)
	{
		return md5($password."sadasdad213165!#!@#");
	}

	/**
	 * 检测验证码
	 * @param  str $vcode 验证码
	 * @return [type]        [description]
	 */
	protected function _vcode($vcode)
	{	

		$vcode = strtolower(trim($vcode));
		$svcode=isset($_SESSION['verify'])?$_SESSION['verify']:'';
		if(empty($vcode)||empty($vcode)){
			$this->_json("验证码不能为空!","400");
		}

     
		$svcode = str_replace(" ","",strtolower(trim($svcode)));	     
		if($vcode != $svcode){
			return true;
		}

		return false;
	}

	/**
	 * 验证email
	 * @param  str $email email
	 * @return [type]        [description]
	 */
	protected function _email($email){
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
			  	return true;
			}

		return false;
	}


	/**
	 * 用户登录
	 * @param  string $username 用户名
	 * @param  string $password 密码
	 * @return array            用户信息
	 */
	public function login($email, $password)
	{
		if(empty($email)){
			throw new Exception("email不能为空", 400);
		}


		if(empty($password)){
			throw new Exception("密码不能为空", 400);
		}

		// $password = $this->_md5($password);

		$sql = "select * from user where email = ? and password = ?";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$email);
		$smt->bindParam(2,$password);
		$smt->execute();
		$user = $smt->fetch(PDO::FETCH_ASSOC);

		if(empty($user)){
			throw new Exception("email或密码错误", 400);
		}

		 $_SESSION["username"] = $user["username"];
		 $_SESSION["email"]	   = $user["email"];
		 $_SESSION["id"]       = $user["id"];
		 $data = array(
				"data" => array(
					"username" =>  $user["username"],
					"email"	   =>  $user["email"],
					"user_id"  =>  $user["id"],
					"token"    => session_id(),
					),
				"message" => "登陆成功",
				"code"    => 200
				);

		 echo json_encode($data);
		 exit;
	}
}

 

// $user = new User($db);
// $user->register("test","123","sgc3","123@qq.com");
// $user->login("test","123");
// $user->run();

 ?>